package com.g13.virtualpethospital.service.Implement;

import com.g13.virtualpethospital.common.EntityCommon;
import com.g13.virtualpethospital.config.AppConfig;
import com.g13.virtualpethospital.entity.base.MultMedia;
import com.g13.virtualpethospital.service.MultMediaService;
import com.g13.virtualpethospital.util.FileUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Title: MultMediaServiceImpl
 * @Author yyj1205
 * @Package com.g13.virtualpethospital.service.Implement
 * @Date 25/3/2024 20:12
 * @description: 多媒体的一个实现
 */
@Service
public class MultMediaServiceImpl implements MultMediaService {
    @Autowired
    private AppConfig appConfig;
    @Override
    public MultMedia addResource(MultipartFile multipartFile, EntityCommon.MultiMediaType type) throws IOException, URISyntaxException {
        String uuid = UUID.randomUUID().toString();
        String ext = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
        String fileName = uuid + "." + ext;
        String filetype = FileUtil.convertMultiMediaType(type);

        File file = new File(appConfig.getFileBasePath()  + File.separator + filetype, fileName);
        FileUtils.writeByteArrayToFile(file,multipartFile.getBytes());
        URI uri = new URI(appConfig.getFileExternHost() + '/' + filetype + '/' + fileName);
        return new MultMedia(type, fileName, uri);
    }

    @Override
    public void deleteResource(String name, EntityCommon.MultiMediaType type) throws IOException {
        File file = new File(appConfig.getFileBasePath() + File.separator + FileUtil.convertMultiMediaType(type), name);
        file.delete();
    }

    @Override
    public List<MultMedia> findResource(String name, EntityCommon.MultiMediaType type) throws IOException, URISyntaxException {
        File file = new File(appConfig.getFileBasePath() + File.separator + FileUtil.convertMultiMediaType(type), name);
        if(!file.exists()) throw new IOException("找不到文件");
        URI uri = new URI(appConfig.getFileExternHost() + '/' + FileUtil.convertMultiMediaType(type) + '/' + name);
        List<MultMedia> multMedia = new ArrayList<>();
        multMedia.add(new MultMedia(type, name, uri));
        return multMedia;
    }
}
